import React, { useEffect, useState } from 'react';
import {
  Box,
  Container,
  Typography,
  Grid,
  Breadcrumbs,
  Link,
  CircularProgress,
} from '@mui/material';
import { useParams, Link as RouterLink } from 'react-router-dom';
import { Implementation, Tag } from '../types';
import { api } from '../services/api';
import ImplementationCard from '../components/CodeImplementation/ImplementationCard';

const TagPage: React.FC = () => {
  const { tagId } = useParams<{ tagId: string }>();
  const [implementations, setImplementations] = useState<Implementation[]>([]);
  const [tag, setTag] = useState<Tag | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const loadTagData = async () => {
      if (!tagId) return;

      setLoading(true);
      try {
        // 加载标签信息
        const tags = await api.getTags();
        const currentTag = tags.find(t => t.id === tagId);
        if (currentTag) {
          setTag(currentTag);
        }

        // 加载带有该标签的实现
        const tagImplementations = await api.getImplementationsByTag(tagId);
        setImplementations(tagImplementations);
      } catch (error) {
        console.error('Error loading tag data:', error);
      } finally {
        setLoading(false);
      }
    };

    loadTagData();
  }, [tagId]);

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '60vh' }}>
        <CircularProgress />
      </Box>
    );
  }

  if (!tag) {
    return (
      <Container>
        <Typography variant="h5" color="error">
          标签不存在
        </Typography>
      </Container>
    );
  }

  return (
    <Container>
      {/* 面包屑导航 */}
      <Breadcrumbs sx={{ my: 2 }}>
        <Link component={RouterLink} to="/" color="inherit">
          首页
        </Link>
        <Typography color="text.primary">标签: {tag.name}</Typography>
      </Breadcrumbs>

      {/* 标签信息 */}
      <Box sx={{ my: 4 }}>
        <Typography variant="h4" gutterBottom>
          {tag.name}
        </Typography>
        <Typography variant="subtitle1" color="text.secondary">
          找到 {implementations.length} 个相关实现
        </Typography>
      </Box>

      {/* 实现列表 */}
      <Grid container spacing={3}>
        {implementations.map((implementation) => (
          <Grid item xs={12} sm={6} md={4} key={implementation.id}>
            <ImplementationCard implementation={implementation} />
          </Grid>
        ))}
        {implementations.length === 0 && (
          <Grid item xs={12}>
            <Typography variant="body1" color="text.secondary" align="center">
              暂无相关实现
            </Typography>
          </Grid>
        )}
      </Grid>
    </Container>
  );
};

export default TagPage;
